package com.projectbox.web;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.projectbox.model.User;
import com.projectbox.service.UserService;
import com.projectbox.utility.EmailUtility;

@Controller
@RequestMapping("/register")
public class RegisterController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private UserService userService;
	private EmailUtility emailUtility;
		
	public void setEmailUtility(EmailUtility emailUtility) {
		this.emailUtility = emailUtility;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String newUserSubmit(@RequestParam(value = "fname", required = true) String firstName, 
			@RequestParam(value = "lname", required = true) String lastName,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "pass", required = true) String password ) {
		logger.debug("form");
		if(this.userService.registerUser(email, password, firstName, lastName)){
			logger.debug("true");
			return "registerSucssess";
		}			
		else {
			logger.debug("false");
			return "redirect:/login";
		}			
	}
	
	@RequestMapping(value = "/checkEmail", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkEstingEmail(
			@RequestParam(value = "email", required = true) String email) {
		
		logger.debug("newUserSubmit");
		logger.debug( "email: " + email);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("valid", false);
		
		
		User user = this.userService.findUser(email);
		if (user != null) {	// someone already register with this email
			return map;
		}
		
		map.put("valid", true);
		return map;
	}
	
}
